#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
化学反应研制完整工作流程示例
Integrated Workflow Example: From Reaction Design to Comprehensive Evaluation

展示从反应设计、验证、能耗分析到经济评估的完整流程
"""

import json
import os
from reaction_validator import ReactionValidator


def example_1_simple_combustion():
    """
    示例1: 简单燃烧反应 - 完整工作流程
    甲烷燃烧: CH4 + 2O2 → CO2 + 2H2O
    """
    print("\n" + "=" * 80)
    print("示例1: 甲烷燃烧反应 - 完整工作流程")
    print("=" * 80)

    # ========== 阶段1: 反应设计 ==========
    print("\n【阶段1】反应设计")
    print("-" * 80)

    equation = "CH4 + 2O2 → CO2 + 2H2O"
    print(f"反应方程式: {equation}")
    print("反应类型: 完全燃烧反应")
    print("反应物: 甲烷(CH4)、氧气(O2)")
    print("产物: 二氧化碳(CO2)、水(H2O)")

    # 物料平衡
    print("\n物料平衡:")
    print("  CH4: 16 g/mol")
    print("  O2: 32 g/mol × 2 = 64 g/mol")
    print("  CO2: 44 g/mol")
    print("  H2O: 18 g/mol × 2 = 36 g/mol")
    print("  总质量: 80 g/mol → 80 g/mol ✅")
    
    # ========== 阶段2: 反应验证 ==========
    print("\n【阶段2】反应有效性验证")
    print("-" * 80)

    validator = ReactionValidator()

    # 准备热力学数据
    thermodynamics = {
        'delta_H': -890.3,  # kJ/mol (强放热)
        'delta_G': -818.0,  # kJ/mol (自发)
        'delta_S': -242.8,  # J/(mol·K)
        'temperature': 298.15  # K
    }

    # 准备反应条件
    conditions = {
        'temperature': 298.15,  # K (常温)
        'pressure': 101.325,    # kPa (常压)
        'stirring_speed': 0,    # rpm (无需搅拌)
        'reaction_time': 60     # minutes
    }

    # 验证反应
    validation = validator.validate_reaction(equation, thermodynamics, conditions)
    print(f"验证状态: {validation.status.value}")
    print(f"验证得分: {validation.score}/100")
    print(f"验证信息: {validation.message}")
    
    # ========== 阶段3: 能耗分析 ==========
    print("\n【阶段3】能耗分析")
    print("-" * 80)

    reaction_data = {
        'thermodynamics': thermodynamics,
        'conditions': conditions,
        'reactants': [{'formula': 'CH4'}, {'formula': 'O2'}],
        'products': [{'formula': 'CO2'}, {'formula': 'H2O'}],
        'reactant_masses': {'CH4': 100.0, 'O2': 400.0},
        'reactant_prices': {'CH4': 3.0, 'O2': 0.5},
        'product_amounts': {'CO2': 275.0, 'H2O': 225.0},  # 理论产量
        'product_prices': {'CO2': 0.1, 'H2O': 0.05},
        'yield_factor': 0.95,
        'electricity_price': 0.8,
        'labor_cost': 500,
        'equipment_depreciation': 200,
        'equipment_investment': 100000,
        'annual_batches': 300
    }
    
    energy = validator.analyze_energy(reaction_data, production_scale=100)
    print(f"总能耗: {energy.total_energy:.2f} kWh")
    print(f"  - 加热能耗: {energy.heating_energy:.2f} kWh")
    print(f"  - 冷却能耗: {energy.cooling_energy:.2f} kWh")
    print(f"  - 机械能耗: {energy.mechanical_energy:.2f} kWh")
    print(f"能效: {energy.energy_efficiency*100:.1f}%")
    print(f"能耗成本: ¥{energy.energy_cost:.2f}")
    
    # ========== 阶段4: 经济性分析 ==========
    print("\n【阶段4】经济性分析")
    print("-" * 80)
    
    economics = validator.analyze_economics(reaction_data, production_scale=100, energy_analysis=energy)
    print(f"原料成本: ¥{economics.raw_material_cost:.2f}")
    print(f"能耗成本: ¥{economics.energy_cost:.2f}")
    print(f"人工成本: ¥{economics.labor_cost:.2f}")
    print(f"设备折旧: ¥{economics.equipment_depreciation:.2f}")
    print(f"总成本: ¥{economics.total_cost:.2f}")
    print(f"产品价值: ¥{economics.product_value:.2f}")
    print(f"利润: ¥{economics.profit:.2f}")
    print(f"利润率: {economics.profit_margin*100:.1f}%")
    print(f"ROI: {economics.roi*100:.1f}%")
    print(f"回收期: {economics.payback_period:.2f} 年")
    print(f"经济可行性: {economics.economic_feasibility}")
    
    # ========== 阶段5: 综合评估 ==========
    print("\n【阶段5】综合评估")
    print("-" * 80)
    
    result = validator.comprehensive_evaluation(equation, reaction_data, production_scale=100)
    print(f"综合评分: {result['overall_score']:.1f}/100")
    print(f"评级: {result['summary']}")
    
    print("\n优化建议:")
    for i, rec in enumerate(result['recommendations'], 1):
        print(f"  {i}. {rec}")
    
    # ========== 阶段6: 生成报告 ==========
    print("\n【阶段6】生成工艺报告")
    print("-" * 80)
    
    report_dir = "data/integrated_example1"
    os.makedirs(report_dir, exist_ok=True)
    
    # 保存完整数据
    report_data = {
        'equation': equation,
        'validation': {
            'status': validation.status.value,
            'score': validation.score,
            'message': validation.message
        },
        'energy_analysis': {
            'total_energy': energy.total_energy,
            'energy_efficiency': energy.energy_efficiency,
            'energy_cost': energy.energy_cost
        },
        'economic_analysis': {
            'total_cost': economics.total_cost,
            'profit': economics.profit,
            'profit_margin': economics.profit_margin,
            'roi': economics.roi,
            'payback_period': economics.payback_period
        },
        'overall_score': result['overall_score'],
        'recommendations': result['recommendations']
    }
    
    report_file = os.path.join(report_dir, "comprehensive_report.json")
    with open(report_file, 'w', encoding='utf-8') as f:
        json.dump(report_data, f, indent=2, ensure_ascii=False)
    
    print(f"✅ 报告已保存: {report_file}")
    
    # ========== 阶段7: 实施决策 ==========
    print("\n【阶段7】实施决策")
    print("-" * 80)
    
    if result['overall_score'] >= 80:
        decision = "✅ 强烈推荐实施"
        color = "绿色"
    elif result['overall_score'] >= 60:
        decision = "⚡ 可以考虑实施，建议优化"
        color = "黄色"
    else:
        decision = "❌ 不建议实施，需要重大改进"
        color = "红色"
    
    print(f"决策建议: {decision}")
    print(f"信号灯: {color}")
    
    return result


def example_2_catalytic_reaction():
    """
    示例2: 催化反应 - Haber-Bosch氨合成
    N2 + 3H2 → 2NH3
    """
    print("\n" + "=" * 80)
    print("示例2: Haber-Bosch氨合成 - 催化反应工作流程")
    print("=" * 80)

    # 阶段1: 反应设计
    print("\n【阶段1】反应设计")
    print("-" * 80)

    equation = "N2 + 3H2 → 2NH3"
    print(f"反应方程式: {equation}")
    print("反应类型: 催化合成反应")
    print("催化剂: 铁基催化剂（Fe₃O₄）")
    print("反应条件: 高温高压（400°C, 200 atm）")

    # 阶段2-7: 完整评估
    
    reaction_data = {
        'thermodynamics': {
            'delta_H': -92.4,
            'delta_G': -33.0,
            'delta_S': -198.8,
            'temperature': 673.15  # 400°C
        },
        'conditions': {
            'temperature': 673.15,
            'pressure': 20000,  # 200 atm
            'stirring_speed': 300,
            'reaction_time': 180
        },
        'reactants': [{'formula': 'N2'}, {'formula': 'H2'}],
        'products': [{'formula': 'NH3'}],
        'reactant_masses': {'N2': 100.0, 'H2': 30.0},
        'reactant_prices': {'N2': 2.0, 'H2': 15.0},
        'product_amounts': {'NH3': 121.6},
        'product_prices': {'NH3': 25.0},
        'yield_factor': 0.15,  # 单程转化率15%
        'electricity_price': 0.8,
        'labor_cost': 800,
        'equipment_depreciation': 500,
        'equipment_investment': 500000,
        'annual_batches': 200
    }
    
    validator = ReactionValidator()
    result = validator.comprehensive_evaluation(equation, reaction_data, production_scale=100)
    
    print(f"\n综合评分: {result['overall_score']:.1f}/100")
    print("\n优化建议:")
    for i, rec in enumerate(result['recommendations'], 1):
        print(f"  {i}. {rec}")
    
    # 特别说明
    print("\n【特别说明】")
    print("Haber-Bosch工艺是工业氨合成的经典工艺:")
    print("  - 高温高压条件（400°C, 200 atm）")
    print("  - 使用铁基催化剂")
    print("  - 单程转化率低，需要循环")
    print("  - 能耗较高，但产品价值高")
    
    return result


def main():
    """主函数"""
    print("╔════════════════════════════════════════════════════════════════════════════╗")
    print("║          化学反应研制完整工作流程 - 集成示例                               ║")
    print("╚════════════════════════════════════════════════════════════════════════════╝")
    
    print("\n本示例展示从反应设计到综合评估的完整工作流程:")
    print("  1. 反应设计")
    print("  2. 反应有效性验证")
    print("  3. 能耗分析")
    print("  4. 经济性分析")
    print("  5. 综合评估")
    print("  6. 生成工艺报告")
    print("  7. 实施决策")
    
    # 运行示例
    result1 = example_1_simple_combustion()
    result2 = example_2_catalytic_reaction()
    
    # 对比结果
    print("\n" + "=" * 80)
    print("示例对比")
    print("=" * 80)
    print(f"\n{'反应':<30} {'综合评分':<15} {'决策建议':<30}")
    print("-" * 80)
    print(f"{'甲烷燃烧':<30} {result1['overall_score']:<15.1f} {'需要优化':<30}")
    print(f"{'氨合成':<30} {result2['overall_score']:<15.1f} {'需要优化':<30}")
    
    print("\n" + "=" * 80)
    print("工作流程演示完成！")
    print("=" * 80)
    print("\n💡 提示:")
    print("  - 查看生成的报告: data/integrated_example1/comprehensive_report.json")
    print("  - 修改反应参数，观察评分变化")
    print("  - 根据优化建议改进工艺")


if __name__ == "__main__":
    main()

